<!DOCTYPE html>
<html lang="ch">
<head>
    <meta charset="utf-8">
    <title>花卉识别程序</title>
    <link rel="stylesheet" href="style.css">
    <style>
        /* 底部容器样式 */
        .footer {
            background-color: #333; /* 底部背景颜色 */
            color: #50a8b0; /* 字体颜色 */
            padding: 10px 0; /* 上下内边距 */
            text-align: center; /* 文本居中 */
            position: fixed; /* 固定位置 */
            bottom: 0; /* 紧贴底部 */
            width: 100%; /* 宽度为全屏 */
        }

        /* 链接样式 */
        .footer a {
            color: #50a8b0; /* 链接颜色 */
            text-decoration: none; /* 去除下划线 */
        }
    </style>
</head>
<body>
<div class="container">
    <h1>智能花卉识别程序</h1>
    <div class="content">
        <div class="flower-recognition">
            <h2>花卉识别</h2>
            <input type="file" id="imageInput" accept="image/*">
            <button id="recognizeButton">识别花卉</button>
            <p id="recognitionResult"></p>
        </div>

    </div>

</div>
<div class="footer">
    <img src="images/beian.jpg" alt="beian" class="left-image">
    <a href="https://beian.mps.gov.cn/#/query/webSearch" rel=\"noreferrer\" target=\"_blank\">津公网安备12011602300027</a>
    <a href="https://beian.miit.gov.cn" id="beian" target="_blank">津ICP备2023006873号-1</a>
</div>
<!--<div class="footer">-->
<!--    <p>花卉识别技术由百度AI提供</p>-->
<!--</div>-->

<script>
    async function getAccessToken(apiKey, secretKey) {
        const accessTokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
        const params = new URLSearchParams({
            grant_type: 'client_credentials',
            client_id: apiKey,
            client_secret: secretKey
        });

        try {
            const response = await fetch(accessTokenUrl, {
                method: 'POST',
                body: params
            });

            const data = await response.json();
            return data.access_token;
        } catch (error) {
            console.error('Error fetching access token:', error);
        }

        return null;
    }

    async function baiduAIFlowerRecognition(imageFile) {
        const apiKey = 'ejCizgR6nz5p4MyHbhdPe1to';
        const secretKey = 'DjakbxQe6KnNY2BESiIYndmNQ5Akynyp';
        const url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant';

        // 将文件转换为Base64
        function convertToBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = function() {
                    resolve(reader.result);
                };
                reader.onerror = reject;
                reader.readAsDataURL(file);
            });
        }

        try {
            const accessToken = '24.2aa7652b4991084f30fed88921a57b69.2592000.1711721381.282335-45506624';
            const base64Image = await convertToBase64(imageFile);
            const base64Formatted = base64Image.split(',')[1]; // 去除Base64前缀

            const response = await fetch(`${url}?access_token=${accessToken}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `image=${encodeURIComponent(base64Formatted)}`
            });

            if (response.ok) {
                const jsonResponse = await response.json();
                if (jsonResponse.result && jsonResponse.result.length > 0) {
                    const flowerName = jsonResponse.result[0].name;
                    return flowerName; // 返回识别出的花名
                } else {
                    return '';
                }
            }
        } catch (error) {
            console.error('Error in flower recognition:', error);
        }
    }




    document.addEventListener('DOMContentLoaded', function() {
        const recognizeButton = document.getElementById('recognizeButton');
        const imageInput = document.getElementById('imageInput');
        const resultDisplay = document.getElementById('recognitionResult');

        recognizeButton.addEventListener('click', async function() {
            const imageFile = imageInput.files[0];
            if (!imageFile) {
                alert('请先选择一张图片');
                return;
            }

            resultDisplay.textContent = '正在识别...';
            try {
                const flowerName = await baiduAIFlowerRecognition(imageFile);
                if (flowerName) {
                    const encodedFlowerName = encodeURIComponent(flowerName);
                    const baikeUrl = `https://baike.baidu.com/item/${encodedFlowerName}`;
                    window.open(baikeUrl, '_blank');
                    resultDisplay.textContent = `相似度最高的花是: ${flowerName}`;
                } else {
                    resultDisplay.textContent = '无法识别';
                }
            } catch (error) {
                resultDisplay.textContent = '识别出错，请稍后重试';
            }
        });
    });


</script>

</body>
</html>